﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace 对称加密
{
    /// <summary>
    /// 使用 AES 算法进行加密，key必须为8位
    /// </summary>
    public static class AES8Utils
    {
        const string KEY_64 = "abc12345"; // 必须为8位
        const string IV_64 = "12345abc";
        static byte[] byKey = Encoding.UTF8.GetBytes(KEY_64);
        static byte[] byIV = Encoding.UTF8.GetBytes(IV_64);
        public static string Encode(string data)
        {
            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
           // int i = cryptoProvider.KeySize;
            MemoryStream ms = new MemoryStream();
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);

            StreamWriter sw = new StreamWriter(cst);
            sw.Write(data);
            sw.Flush();
            cst.FlushFinalBlock();
            sw.Flush();
            return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
        }
        public static string Decode(string data)
        {
            byte[] byEnc;
            try
            {
                byEnc = Convert.FromBase64String(data);
            }
            catch
            {
                return null;
            }

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            System.IO.MemoryStream ms = new MemoryStream(byEnc);
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cst);
            return sr.ReadToEnd();
        }
    }
}
